<script setup lang="ts">
import { ref, toRefs, watch } from 'vue'

import { message } from 'ant-design-vue'

import { toYuan } from '@/hooks/util'
import * as templateApi from '../../../api/template'

import AddRule from './AddTemplateRule.vue'

const props = defineProps({
  templateId: String,
  type: Number,
})
const { type } = toRefs(props)

const newTemplateId = ref('')

const addRuleRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
})

let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  channel: number
  [propName: string]: any
}

const searchParams = ref<SearchParams>({
  channel: type?.value, // 闲鱼
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
  name: '',
  ticketChannel: '',
})

// 渠道下拉框
const changeTicketChannel = (e: any) => {
  if (!e) {
    delete searchParams.value.ticketChannel
  }
}

const ticketChannelList = ref([
  {
    label: '麻花电影票',
    value: 3,
  },
  {
    label: '守兔电影票',
    value: 11,
  },
  {
    label: '守兔',
    value: 7,
  },
  {
    label: '芒果电影票',
    value: 5,
  },
  {
    label: '哈哈电影快票',
    value: 9,
  },
  {
    label: '星驰电影票',
    value: 8,
  },
  {
    label: '影划算电影票',
    value: 10,
  },
])

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  getList()
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  searchParams.value.name = ''
  searchParams.value.ticketChannel = ''

  getList()
}

const dataSource = ref([])
const columns = [
  {
    title: '名称/院线',
    key: 'name',
    width: 400,
  },
  {
    title: '排除影院',
    key: 'cinemaList',
    width: 400,
  },
  {
    title: '报价出票模式',
    key: 'ticketChannel',
    width: 530,
  },
  {
    title: '报价调整类型/报价方式',
    key: 'finalPriceAdjustType',
    width: 400,
  },
  {
    title: '报价金额/是否限价',
    key: 'quotationAmount',
    width: 400,
  },
  {
    title: '限价金额 ',
    key: 'status',
    width: 400,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
    align: 'center',
  },
]

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await templateApi.getSimpleRuleList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list.map((item: any) => {
        item.statusFlag = false
        return item
      })
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

//删除规则
const delRule = async (id: any) => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await templateApi.deleteTemplateRule({
      id: id,
      groupId: newTemplateId.value,
    })
    if (state === 200) {
      message.success('删除成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

//添加规则
const addRule = () => {
  addRuleRef.value.showModal(type?.value, newTemplateId.value)
}

//编辑规则
const edit = (record: any) => {
  addRuleRef.value.showModal(type?.value, newTemplateId.value, record)
}

defineExpose({
  getList,
})

watch(
  () => ({ ...props }),
  (newVal, oldVal) => {
    if (newVal.templateId) {
      newTemplateId.value = newVal.templateId
      searchParams.value.groupId = newTemplateId.value
      getList()
    }
  },
  { deep: true, immediate: true },
)
</script>

<template>
  <a-card style="overflow-x: scroll">
    <AddRule ref="addRuleRef" @refresh="getList"></AddRule>

    <div class="header"></div>

    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="searchParams">
        <a-form-item label="名称" name="name">
          <a-input v-model:value="searchParams.name" placeholder="名称" />
        </a-form-item>

        <a-form-item label="渠道" name="ticketChannel">
          <a-select
            v-model:value="searchParams.ticketChannel"
            placeholder="渠道"
            style="width: 150px"
            allowClear
            @change="changeTicketChannel"
          >
            <a-select-option
              v-for="(item, index) in ticketChannelList"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button type="primary" style="margin-left: 10px" @click="addRule">添加规则</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div style="height: 20px"></div>

    <a-table
      style="overflow-x: scroll"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="changePage"
      rowKey="id"
      :scroll="{ x: 100 }"
    >
      <template #emptyText>
        <a-empty description="暂无数据" />
      </template>

      <template #headerCell="{ column }"></template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'name'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="规则名称">
              <a-tooltip placement="top">
                <template #title>
                  <span>{{ record.name }}</span>
                </template>
                <span class="hiddenText">{{ record.name }}</span>
              </a-tooltip>
            </a-descriptions-item>

            <a-descriptions-item label="院线">
              <a-tooltip placement="top">
                <template #title>
                  <a-tag color="blue" v-for="item in record.lineList" :key="item">
                    {{ item.lineName }}
                  </a-tag>
                </template>
                <div class="hiddenText">
                  <a-tag
                    style="line-height: 16px"
                    color="blue"
                    v-for="item in record.lineList"
                    :key="item"
                  >
                    {{ item.lineName }}
                  </a-tag>
                </div>
              </a-tooltip>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-if="column.key === 'cinemaList'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="排除影院">
              <a-tooltip placement="top">
                <template #title>
                  <a-tag color="blue" v-for="item in record.cinemaList" :key="item">
                    {{ item.name }}
                  </a-tag>
                </template>
                <div class="hiddenText">
                  <a-tag
                    style="line-height: 16px"
                    color="blue"
                    v-for="item in record.cinemaList"
                    :key="item"
                  >
                    {{ item.name }}
                  </a-tag>
                </div>
              </a-tooltip>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'ticketChannel'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
            <a-descriptions-item label="询价渠道">
              <a-tag color="blue" v-if="record.ticketChannel == 3">麻花电影票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 11">守兔电影票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 7">守兔</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 6">哈哈电影票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 5">芒果电影票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 9">哈哈电影快票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 8">星驰电影票</a-tag>
              <a-tag color="blue" v-if="record.ticketChannel == 10">影划算电影票</a-tag>
            </a-descriptions-item>

            <a-descriptions-item label="报价渠道">
              <a-tag color="blue" v-if="record.matchChannel == 3">麻花电影票（可限价）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 11">守兔电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 7">守兔电影票（可限价）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 5">芒果电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 6">哈哈电影票</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 9">哈哈电影快票（固定9折）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 8">星驰电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.matchChannel == 10">影划算电影票（可限价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 3">麻花电影票（可限价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 6">哈哈电影票</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 11">守兔电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 7">守兔电影票（可限价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 5">芒果电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 9">
                哈哈电影快票（固定9折）
              </a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 8">星驰电影票（一口价）</a-tag>
              <a-tag color="blue" v-if="record.slaveMatchChannel == 10">
                影划算电影票（可限价）
              </a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'finalPriceAdjustType'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '140px' }">
            <a-descriptions-item label="报价调整类型">
              <span v-if="record.finalPriceAdjustType == 1">四舍五入到整数元</span>
              <span v-if="record.finalPriceAdjustType == 2">四舍五入到元-0.1</span>
              <span v-if="record.finalPriceAdjustType == 3">到0.5/整数元</span>
              <span v-if="record.finalPriceAdjustType == 0">不调整</span>
            </a-descriptions-item>

            <a-descriptions-item label="报价方式">
              <span v-if="record.quotationType == 1">加法</span>
              <span v-if="record.quotationType == 2">减法</span>
              <span v-if="record.quotationType == 3">比例（百分比加法）</span>
              <span v-if="record.quotationType == 4">比例（百分比减法）</span>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'quotationAmount'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
            <a-descriptions-item label="报价金额">
              <span v-if="record.quotationType == 1">
                预估成本
                <span style="color: red">+</span>
                {{ Math.abs(toYuan(record.discount) as any) }} ￥
              </span>
              <span v-if="record.quotationType == 2">
                预估成本
                <span style="color: red">-</span>
                {{ Math.abs(toYuan(record.discount) as any) }} ￥
              </span>
              <span v-if="record.quotationType == 3">
                预估成本
                <span style="color: red">*</span>
                (1 + {{ record.percent }}%)
              </span>
              <span v-if="record.quotationType == 4">
                预估成本
                <span style="color: red">*</span>
                (1 {{ record.percent }}%)
              </span>
            </a-descriptions-item>

            <a-descriptions-item label="是否限价">
              <a-tag color="blue" v-if="record.enableLimitPrice == 1">启用</a-tag>
              <a-tag color="red" v-if="record.enableLimitPrice == 0">不启用</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'status'">
          <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
            <a-descriptions-item label="单张限价">
              <div v-if="record.limitPrice >= 0">【报价】 + {{ record.limitPrice / 100 }}</div>
              <div v-if="record.limitPrice < 0">【报价】 - {{ (0 - record.limitPrice) / 100 }}</div>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space>
            <a @click="edit(record)">编辑</a>
            <a-popconfirm
              title="确定删除？"
              ok-text="是"
              cancel-text="否"
              @confirm="delRule(record.id)"
            >
              <a>删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </a-card>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}
</style>
